
class ShibbolethController < ApplicationController
  include Shibboleth
  before_filter :test_data, lambda { |c| Rails.env == 'development' }
  unloadable

  # Feeds the plugin's images from the plugin/public/images folder
  def images 
    file_name = params[:id] + '.' + params[:format]
    dir = params[:path]
    path = dir.blank? ? file_name : File.join(dir, file_name)
    file_path = Shibboleth.root('public', 'images', path)
    send_file file_path, :type => 'image/' + params[:format], :disposition => 'inline'
  end
  
  # Feeds the plugin's stylesheets from the plugin/public/stylesheets folder
  def stylesheets 
    file_name = params[:id] + '.' + params[:format]
    dir = params[:path]
    path = dir.blank? ? file_name : File.join(dir, file_name)
    file_path = Shibboleth.root('public', 'stylesheets', path)
    send_file file_path, :type => Mime::CSS, :disposition => 'inline'
  end
  
  # Login action. Handle posts from the login screen by doing a redirect
  # if no uri is provided redirect to the secured uri /shibboleth/login
  def login_direct    
    if uri = params[:login_uri] 
      redirect_to uri
    else
      redirect_to '/shibboleth/login'
    end
  end
  
  #Login action. The route pointing to this action should be protected
  #by a Shibboleth directive
  def login
    to = request.env[:HTTP_REFERER]
    to = to.blank? ? '/' : to
    
    if application_loggedin?
      redirect_to to
      return
    end
    
    Shibboleth::authenticate(request) do |user|
      application_login user      
    end
    redirect_to to
  end
  
  #logout action
  def logout
    if application_logout
      flash[:notice] = t('shibboleth.logout_success_message') 
    end
    redirect_to '/'
  end

  # Edit settings
  def settings
    if request.post? 
      Shibboleth.settings = params[:settings]      
    end
    @settings = Shibboleth.settings
    @text_size = 50
    render 'shibboleth/_settings'
  end
  
  protected
  
  #Application specific functions. They should be overriden in a a child class
  
  #Returns true if somebody is already logged into the application
  def application_loggedin?
    false
  end

  #Login a user.
  #Returns true if login was successful. False otherwise.
  def application_login(user)
    return false
  end

  #Logout from the application
  #Returns true on success, false otherwise.
  def application_logout
    return true
  end
  
  private
  
  #add test data to simulate remote user's data
  def test_data
    unless Rails.env == 'development'
      return false
    end
    require Shibboleth.root('test', 'aai.rb')
    Shibboleth::Test::Aai.user request
  end

end